package dao

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"
	__ "user-srv/basic/proto"
	"user-srv/handler/models"
)

// 会员添加
func MemberAdd(in *__.MemberAddReq) (*models.Member, error) {
	var member models.Member
	var memberLevel models.MemberLevel
	memberNo := rand.Intn(90000) + 10000

	member.UserId = in.UserId
	err := member.GetMemberUser()
	if err != nil {
		return nil, fmt.Errorf("用户会员详情查找失败")
	}
	if member.Id != 0 {
		return nil, fmt.Errorf("用户已存在会员")
	}

	member.UserId = in.UserId                //用户id
	member.MemberNo = strconv.Itoa(memberNo) //会员编号

	memberLevel.Level = int32(in.LeveId)
	err = memberLevel.MemberLevelFindByLevel()
	if err != nil {
		return nil, fmt.Errorf("会员等级查找失败")
	}
	if memberLevel.Id == 0 {
		return nil, fmt.Errorf("会员等级不存在")
	}

	member.LeveId = in.LeveId //等级
	member.TotalPoints = 0

	joinTime := time.Now()
	overTime := models.CountMemberOverTime(joinTime, 1)

	member.JoinTime = joinTime
	member.OverTime = overTime

	err = member.MemberAdd()
	if err != nil {
		return nil, fmt.Errorf("会员添加失败")
	}

	return &member, nil
}

// 用户会员详情
func MemberDetails(in *__.MemberDetailsReq) (*models.Member, error) {
	var member models.Member
	member.UserId = in.UserId //用户id
	err := member.MemberDetails()
	if err != nil {
		return nil, fmt.Errorf("用户会员详情查找失败")
	}

	return &member, nil
}
